package com.xing.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xing.server.base.R;
import com.xing.server.mapper.MailLogMapper;
import com.xing.server.pojo.Employee;
import com.xing.server.mapper.EmployeeMapper;
import com.xing.server.pojo.MailConstants;
import com.xing.server.pojo.MailLog;
import com.xing.server.pojo.RPageBean;
import com.xing.server.service.IEmployeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xingfuhao
 * @since 2021-11-28
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
//    @Autowired
//    private RabbitTemplate rabbitTemplate;
    @Resource
    private MailLogMapper mailLogMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 获取所有员工列表 分页
     * @param currentPage
     * @param size
     * @param employee
     * @param beginDateScope
     * @return
     */
    @Override
    public RPageBean getEmployeeByPage(Integer currentPage, Integer size, Employee employee, LocalDate[] beginDateScope) {
        //开启分页
        Page<Employee> page = new Page<>(currentPage,size);
        IPage<Employee> employeeByPage = employeeMapper.getEmployeeByPage(page, employee, beginDateScope);
        //获取分页的值赋值给公共返回对象。
        RPageBean rPageBean = new RPageBean(employeeByPage.getTotal(),employeeByPage.getRecords());
        return rPageBean;
    }

    /**
     * 获取工号
     * @return
     */
    @Override
    public R getMaxWorkId() {
        //获取最大值的maps集合,k和v。key为max(workID) value:00000100
        List<Map<String, Object>> maps = employeeMapper.selectMaps(
                new QueryWrapper<Employee>().select("max(workID)"));
        //取出工号，原有最大值加1
        int i = Integer.parseInt(maps.get(0).get("max(workID)").toString()) + 1;
        //格式化为String类型，为八位值，0来补充八位。
        return R.success(null,String.format("%08d", i));
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @Override
    public R addEmp(Employee employee) {
        //处理合同期限，保留2位小数
        LocalDate beginContract = employee.getBeginContract();
        LocalDate endContract = employee.getEndContract();
        long days = beginContract.until(endContract, ChronoUnit.DAYS);
        //格式化数据
        DecimalFormat decimalFormat = new DecimalFormat("##.00");
        //设置合同期限
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days/365.00)));
        if(1==employeeMapper.insert(employee)){
            //消息队列避免消息的重复消费
            //给每条消息设置消息的全局的唯一id
//            UUID uuid = new UUID();
//            UUID uuid1 = uuid.randomUUID();
//            String s = uuid1.toString();
            List<Employee> employee1 = employeeMapper.getEmployee(employee.getId());
            Employee employee22 = employee1.get(0);

            //消息队列避免消息的重复消费
            //给每条消息设置消息的全局的唯一id
            //数据库记录发送的消息
//            String msgId = UUID.randomUUID().toString();
            String msgId = "123456";
            MailLog mailLog = new MailLog();
            mailLog.setMsgId(msgId);
            mailLog.setEid(employee.getId());
            mailLog.setStatus(0);
            mailLog.setRouteKey(MailConstants.MAIL_ROUTING_KEY_NAME);
            mailLog.setExchange(MailConstants.MAIL_EXCHANGE_NAME);
            mailLog.setCount(0);
            mailLog.setTryTime(LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT));
            mailLog.setCreateTime(LocalDateTime.now());
            mailLog.setUpdateTime(LocalDateTime.now());
            mailLogMapper.insert(mailLog);

           //发送消息
           rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,
                   MailConstants.MAIL_ROUTING_KEY_NAME,
                   employee22, new CorrelationData(msgId));

//            之前使用的
//            rabbitTemplate.convertAndSend("mail.welcome",employee22);

//            //发送消息
//            List<Employee> employee1 = employeeMapper.getEmployee(employee.getId());
//            Employee employee2 = employee1.get(0);
//            for(int i=0;i<10;i++)
//
//            {
//                rabbitTemplate.convertAndSend("mail.welcome", employee2);
//
//            }

            return R.success("添加成功！");
        }
        return R.error("添加失败！");
    }

    /**
     * 查询员工
     * @param id
     * @return
     */
    @Override
    public List<Employee> getEmployee(Integer id) {
        return employeeMapper.getEmployee(id);
    }

    /**
     * 获取所有员工的套帐 分页
     * @param currentPage
     * @param size
     * @return
     */
    @Override
    public RPageBean getAllEmployeeWithSalary(Integer currentPage, Integer size) {
        //开启分页
        Page<Employee> page = new Page<>(currentPage,size);
        IPage<Employee> employeeIPage=employeeMapper.getAllEmployeeWithSalary(page);
        RPageBean rPageBean = new RPageBean(employeeIPage.getTotal(),employeeIPage.getRecords());
        return rPageBean;
    }
}
